<template>
  <div class="content">
    <el-card>
      <template #header>
        <div class="header">登录</div>
      </template>
      <el-form :model="formData" ref="formRef" :rules="login_rules">
        <el-form-item label="账号" prop="account">
          <el-input v-model="formData.account" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end items-center">
          <el-button type="primary" @click="submit(formRef)">登录</el-button>
          <el-button type="primary" @click="register(formRef)">注册</el-button>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { FormInstance } from "element-plus";
import { Login } from "@/api/login";
import { login_rules } from "@/rules/login";
import { useAppStore } from "@/store/app";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { GetMenus } from "@/api/menus";


const appStore = useAppStore()
const router = useRouter()
interface FormDataInter {
  account: string
  password: string
}

const formData = ref<FormDataInter>({} as FormDataInter)
const formRef = ref<FormInstance>()

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await Login(formData.value)
      if (res.code === 200) {
        ElMessage.success('登录成功')
        appStore.setToken(res.token)
        appStore.setUserInfo(res.data)
        getMenus()
        router.push('/')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const getMenus = async () => {
  const res = await GetMenus()
  if(res.code === 200) {
    appStore.setMenus(res.data)
  }
}

const register = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    console.log(valid, fields)
  })
}
</script>

<style scoped lang="less">
.content {
  height: 100%; /* 根据需要调整高度 */
  width: 100%; /* 根据需要调整宽度 */
  background: linear-gradient(45deg, #ff9a9e, #fad0c4, #fbc2eb, #a18cd1, #8fd3f4);
  background-size: 400% 400%;
  animation: gradientBG 15s ease infinite;
  display: flex;
  justify-content: center;
  align-items: center;
}

@keyframes gradientBG {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>